package jblip.util;

import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import jblip.resources.Media;

/**
 * Loads pictures from <i>picture</i> resources.
 * 
 * <p>
 * This class provides two functionalities:
 * <ul>
 * <li>loads data from <code>Picture</code> objects and stores them as a
 * <i>Java Swing</i> <code>Icon</code> resources.</li>
 * <li>creates cache for already loaded pictures, so each picture is read only
 * once.</li>
 * </ul>
 * </p>
 * 
 * @author Krzysztof Sroka
 * @since 0.1
 */
public class SwingPictureLoader {
  private final static Map<Integer, Icon> loaded_pictures;

  static {
    loaded_pictures = new HashMap<Integer, Icon>();
  }

  /**
   * Gets a picture from cache or loads it from the web.
   * 
   * <p>
   * Shorthand for <code>getImage(pict, <b>true</b>)</code>
   * </p>
   * 
   * @param pict <i>picture</i> resource containing picture's data.
   * @return Picture a <i>Java Swing</i> representation for the given resource
   *         object.
   */
  public static Icon getImage(Media pict) {
    return getImage(pict, true);
  }

  /**
   * Gets a picture. 
   * 
   * @param pict <i>picture</i> resource containing picture's data.
   * @param use_cache indicates whether cache should be used (<code>true</code>)
   *   or ignored (<code>false</code>).
   * @return Picture a <i>Java Swing</i> representation for the given resource
   *         object.
   */
  public static Icon getImage(Media pict, boolean use_cache) {
    if (!use_cache || loaded_pictures.get(pict.getID()) == null) {
      Icon ic = new ImageIcon(pict.getURL());
      loaded_pictures.put(pict.getID(), ic);
    }

    return loaded_pictures.get(pict.getID());
  }
}
